<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item prop="name">
        <el-input v-model="queryParams.name" :placeholder="$t('iot.enterProgramName')" clearable size="small" @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">{{ $t('common.search') }}</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">{{ $t('common.reset') }}</el-button>
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="small" @click="handleAdd" v-hasPermi="['iot:hgitems:add']">{{ $t('common.add') }}</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="small" :disabled="single" @click="handleUpdate" v-hasPermi="['iot:hgitems:edit']">{{ $t('common.edit') }}</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="small" :disabled="multiple" @click="handleDelete" v-hasPermi="['iot:hgitems:remove']">{{ $t('common.delete') }}</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"/>
    </el-row>
    <el-table v-loading="loading" :data="hgitemsList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="45" align="center"/>
      <el-table-column :label="$t('iot.customer')" align="center" prop="nickName" width="155"/>
      <el-table-column :label="$t('iot.project')" align="center" prop="projectname" width="155"/>
      <el-table-column :label="$t('iot.programNo')" align="center" prop="id" />
      <el-table-column :label="$t('iot.programName')" align="center" prop="name" />
      <el-table-column :label="$t('iot.width')" align="center" prop="width" />
      <el-table-column :label="$t('iot.height')" align="center" prop="height" />
      <el-table-column :label="$t('iot.fontSize')" align="center" prop="fsize" />
      <el-table-column :label="$t('iot.textContent')" align="center" prop="remark" width="161" :show-overflow-tooltip="true"/>
      <el-table-column :label="$t('common.createTime')" align="center" prop="createTime" width="156">
        <template slot-scope="scope">{{scope.row.createTime}}</template>
      </el-table-column>
      <el-table-column :label="$t('iot.creator')" align="center" prop="createBy"/>
      <el-table-column :label="$t('common.updateTime')" align="center" prop="updateTime" width="156">
        <template slot-scope="scope">{{scope.row.updateTime||$t('iot.notUpdated')}}</template>
      </el-table-column>
      <el-table-column :label="$t('common.operation')" align="center" class-name="small-padding fixed-width" width="108">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)" v-hasPermi="['iot:hgitems:edit']">{{ $t('common.edit') }}</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)" v-hasPermi="['iot:hgitems:remove']">{{ $t('common.delete') }}</el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" :page-sizes="pageSizes" @pagination="getList"/>
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <div class="scrollable-content">
        <el-form ref="form" :model="form" :rules="rules" label-width="96px">
          <el-form-item :label="$t('iot.customerName')" prop="customerId">
            <el-select v-model="form.customerId" :placeholder="$t('iot.selectCustomerName')" filterable style="width:100%" @change="handleNicknameChange">
              <el-option v-for="item in options" :key="item.userId" :label="item.nickName" :value="item.userId"/>
            </el-select>
          </el-form-item>
          <el-form-item :label="$t('iot.projectName')" prop="projectId">
            <el-select v-model="form.projectId" :placeholder="$t('iot.selectProjectName')" filterable style="width:100%" @change="handleProjectnameChange">
              <el-option v-for="item in projectnameOptions" :key="item.id" :label="item.projectname" :value="item.id"/>
            </el-select>
          </el-form-item>
          <el-form-item :label="$t('iot.programName')" prop="name">
            <el-input v-model="form.name" :placeholder="$t('iot.enterProgramName')" />
          </el-form-item>
          <el-form-item :label="$t('iot.width')" prop="width">
            <el-input-number v-model="form.width" :placeholder="$t('iot.enterWidth')" :min="0"/>
          </el-form-item>
          <el-form-item :label="$t('iot.height')" prop="height">
            <el-input-number v-model="form.height" :placeholder="$t('iot.enterHeight')" :min="0"/>
          </el-form-item>
          <el-form-item :label="$t('iot.imageGroup')" prop="images">
            <fileUploadd v-model="form.images" style="width:100%"/>
          </el-form-item>
          <el-form-item :label="$t('iot.imagePlayTime')" prop="imgPTime">
            <el-input-number v-model="form.imgPTime" :placeholder="$t('iot.singleImagePlayTime')" :min="0"/>
          </el-form-item>
          <el-form-item :label="$t('iot.video')">
            <fileUploadd v-model="form.attachfile" style="width:100%"/>
          </el-form-item>
          <el-form-item :label="$t('iot.fontSize')" prop="fsize">
            <el-input-number v-model="form.fsize" :placeholder="$t('iot.enterFontSize')" />
          </el-form-item>
          <el-form-item :label="$t('iot.textContent')" prop="remark">
            <el-input type="textarea" v-model="form.remark" :placeholder="$t('iot.enterTextContent')" />
          </el-form-item>
          <el-form-item :label="$t('iot.textPlayTime')" prop="textPTime">
            <el-input-number v-model="form.textPTime" :placeholder="$t('iot.enterTextPlayTime')" :min="0"/>
          </el-form-item>
        </el-form>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">{{ $t('common.confirm') }}</el-button>
        <el-button @click="cancel">{{ $t('common.cancel') }}</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listHgitems, getHgitems, delHgitems, addHgitems, updateHgitems } from "@/api/iot/hgitems";
import { listUser } from '@/api/iot/tool'
import { listProject } from '@/api/iot/faproject'
export default {
  name: "Hgitems",
  data() {
    return {
      pageSizes: [10,20,30,50],
      options: [],
      projectnameOptions: [],
      loading: true,
      ids: [],
      single: true,
      multiple: true,
      showSearch: true,
      total: 0,
      hgitemsList: [],
      title: "",
      open: false,
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        adminId: null,
        customerId: null,
        projectId: null,
        name: null,
        type: null,
        width: null,
        height: null,
        fsize: null,
        json: null,
        refreshtime: null,
        createtime: null,
        updatetime: null,
        deletetime: null,
        weigh: null,
        switch: null,
        state: null,
        lids: null,
        images: null,
        attachfile: null,
        textPTime: null,
        imgPTime: null,
        mp4PTime: null
      },
      form: {},
      rules: {
        customerId: [{ required: true, message: this.$t('iot.customerNameRequired'), trigger: "blur" }],
        projectId: [{ required: true, message: this.$t('iot.projectNameRequired'), trigger: "blur" }],
        name: [{ required: true, message: this.$t('iot.programNameRequired'), trigger: "blur" }],
      }
    };
  },
  created() {
    this.getList();
    this.fetchUsers();
    this.fetchProjectnames();
  },
  methods: {
    async fetchUsers() {
      try {
        const response = await listUser();
        var resList=response.rows;
        if (response && resList) {
          this.options = resList.map(user => ({
            userId: user.userId,
            nickName: user.nickName
          }));
        }
      } catch (error) {
        console.error('1', error);
      }
    },
    async fetchProjectnames() {
      try {
        const response = await listProject();
        var resList=response.rows;
        if (response && resList) {
          this.projectnameOptions = resList.map(item => ({
            id: item.id,
            projectname: item.projectname,
          }));
          console.log("2", this.projectnameOptions);
        } else {
          console.error('Invalid response format:', response);
        }
      } catch (error) {
        console.error('Error fetching project names:', error);
      }
    },
    handleNicknameChange(selectedId) {
      const selectedOption = this.options.find(option => option.userId === selectedId);
      if (selectedOption) {
        this.form.customerId = selectedOption.userId;
      }
    },
    handleProjectnameChange(selectedId) {
      const selectedOption = this.projectnameOptions.find(option => option.id === selectedId);
      if (selectedOption) {
        this.form.projectId = selectedOption.id;
      } else {
        console.error('No matching data found for value:', value);
      }
    },
    getList() {
      this.loading = true;
      listHgitems(this.queryParams).then(response => {
        this.hgitemsList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    cancel() {
      this.open = false;
      this.reset();
    },
    reset() {
      this.form = {
        customerId: null,
        projectId: null,
        id: null,
        adminId: null,
        name: null,
        type: null,
        width: null,
        height: null,
        fsize: null,
        remark: null,
        json: null,
        refreshtime: null,
        createtime: null,
        updatetime: null,
        deletetime: null,
        weigh: null,
        switch: null,
        state: null,
        lids: null,
        images: null,
        attachfile: null,
        textPTime: 10,
        imgPTime: 10,
        mp4PTime: null
      };
      this.resetForm("form");
    },
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = this.$t('common.add');
    },
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getHgitems(id).then(response => {
        this.form = response.data;
        console.log("3", response.data);
        this.open = true;
        this.title = this.$t('common.edit');
      });
    },
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateHgitems(this.form).then(response => {
              if(response != undefined){
                this.$modal.msgSuccess(this.$t('common.editSuccess'));
              }
              this.open = false;
              this.getList();
            });
          } else {
            addHgitems(this.form).then(response => {
              if(response != undefined){
                this.$modal.msgSuccess(this.$t('common.addSuccess'));
              }
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm(
        this.$t('common.confirmDelete') + ' "' + ids + '" ' + this.$t('common.dataItem') + '？',
        this.$t('navbar.tip'),
        {
          confirmButtonText: this.$t('common.confirm'),
          cancelButtonText: this.$t('common.cancel'),
          type: 'warning'
        }
      ).then(() => {
        return delHgitems(ids);
      }).then(() => {
        this.getList();
        this.$message({
          type: 'success',
          message: this.$t('common.operationSuccess')
        });
      }).catch(() => {});
    }
  }
};
</script>

<style>
.scrollable-content {
  max-height: 80vh;
  overflow-y: scroll;
  padding-right: 10px;
}
.scrollable-content::-webkit-scrollbar {
  width: 8px;
}
.scrollable-content::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 4px;
}
.scrollable-content::-webkit-scrollbar-thumb {
  background: #c0c0c0;
  border-radius: 4px;
}
.scrollable-content::-webkit-scrollbar-thumb:hover {
  background: #a0a0a0;
}
</style>
